package xlingpaper.xxe;

import java.awt.GraphicsEnvironment;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;

import com.xmlmind.guiutil.Alert;
import com.xmlmind.xml.doc.Constants;
import com.xmlmind.xml.doc.Document;
import com.xmlmind.xml.doc.Element;
import com.xmlmind.xml.doc.Inclusion;
import com.xmlmind.xml.doc.InclusionException;
import com.xmlmind.xml.doc.Traversal;
import com.xmlmind.xml.doc.XNode;
import com.xmlmind.xml.name.Name;
import com.xmlmind.xml.wxs.validate.ValidationErrors;
import com.xmlmind.xml.xinclude.XInclude;
import com.xmlmind.xml.xpath.EvalException;
import com.xmlmind.xml.xpath.ParseException;
import com.xmlmind.xml.xpath.XPathUtil;
import com.xmlmind.xmledit.view.DocumentView;

import com.xmlmind.xmledit.cmd.RecordableCommand;
import com.xmlmind.xmledit.cmd.validate.CheckValidityDialog;
import com.xmlmind.xmledit.edit.MarkManager;

public class GetXIncludesAndImageFiles extends RecordableCommand {
    boolean m_showAlerts = false; // used for debugging

    public boolean prepare(DocumentView docView, String parameter, int x, int y) {
	MarkManager markManager = docView.getMarkManager();
	if (markManager == null) {
	    return false;
	}

	Element editedElement = docView.getSelectedElement(/* implicit */true);
	if (editedElement == null) {
	    return false;
	}
	docView.getElementEditor().editElement(editedElement);
	return true;
    }

    protected Object doExecute(DocumentView docView, String parameter, int x, int y) {
	try {
	    final int kMaxFiles = 10000;
	    final String sDocumentPath = parameter;

	    Document doc = docView.getDocument();
	    Traversal.traverse(doc.getRootElement(), new Traversal.HandlerBase() {
		    String[] asFileNames = new String[kMaxFiles];
		    int iCount = 0;
		public Object enterElement(Element element) {
		    Inclusion inclusion = element.getInclusion();

		    if (inclusion != null) {
			//System.err.println("found inclusion:" + inclusion.toString());
			XInclude xinclude = (XInclude) inclusion;
			URL url = xinclude.href;
			System.err.println("URL external form = '" + url.toExternalForm() + "'");
			System.err.println("URL to string = '" + url.toString() + "'");
			try {
			    System.err.println("URL to URI = '" + url.toURI().toString() + "'");
			} catch (URISyntaxException e) {
			    // TODO Auto-generated catch block
			    e.printStackTrace();
			}
			String sProtocol = url.getProtocol();
			if ("file".equals(sProtocol)) {
			    String sFile = url.getFile();
			    if ("/".equals(sFile.substring(0,1)) && ":".equals(sFile.substring(2,3))) {
				sFile = sFile.substring(1);
			    }
			    sFile = fixupImageFile(sDocumentPath, sFile);
			    System.err.println("file name = '" + sFile + "'");
			    asFileNames[iCount] = sFile;
			}

		    }
		    return null;
		}
	    });

	} catch (Exception e) {
	    Alert.showError(docView.getPanel(), "doExecute: Exception caught:" + e.getMessage());
	    return e.getMessage();
	}
	return "allClear";
    }

    private String fixupImageFile(String sDocumentPath, String imageFile) {
	String operatingSystem = System.getProperty("os.name");
	if (operatingSystem.contains("Windows")) {
	    // need to change any '/' to '\' in file name
	    imageFile = imageFile.replace("/", "\\");
	}
	if (imageFile.startsWith("..")) {
	    imageFile = sDocumentPath + System.getProperty("file.separator") + imageFile;
	}
	if (imageFile.startsWith("file:\\\\\\")) {
	    imageFile = imageFile.substring(8);
	}
	imageFile = imageFile.replace("%20", " ");
	imageFile = imageFile.replace("%27", "'");
	imageFile = imageFile.replace("%7E", "~");
	return imageFile;
    }
    // For debugging
    private void showAlert(DocumentView docView, String msg) {
	if (m_showAlerts) {
	    Alert.showError(docView.getPanel(), msg);
	}
    }
}
